package com.doxiaopu.students.utils;

import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;

import java.io.IOException;
import java.io.InputStream;

public class FtpUtil {
    //ftp服务器ip地址
    private static final String FTP_ADDRES = "192.168.16.173";
    //ftp服务器ip地址
    private static final int FTP_PORT = 21;
    //ftp服务器ip地址
    private static final String FTP_USERNAME = "wgj";
    //ftp服务器ip地址
    private static final String FTP_PASSWORD= "root";
    //ftp服务器ip地址
    private static final String FTP_BASEPATH = "/home/wgj/nginx/html/images";

    public static boolean uploadFile(String fileName, InputStream input)  {
        boolean success = false;
        FTPClient ftp = new FTPClient();
        try {
            int reply;
            ftp.connect(FTP_ADDRES,FTP_PORT); //连接FTP服务器
            ftp.login(FTP_USERNAME,FTP_PASSWORD);
            reply = ftp.getReplyCode();
            if(!FTPReply.isPositiveCompletion(reply)){
                ftp.disconnect();
                return false;
            }
            ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
            ftp.makeDirectory(FTP_BASEPATH);
            ftp.changeWorkingDirectory(FTP_BASEPATH);
            ftp.enterLocalActiveMode();
            ftp.storeFile(fileName,input);
            input.close();
            ftp.logout();
            success = true;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (ftp.isConnected()){
                try {
                    ftp.disconnect();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        return success;
    }
}
